package com.cnbot.aimolib.utils;

import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import com.aimall.sdk.extractor.ImoFaceExtractor;
import java.io.File;
import java.io.FileOutputStream;

/**
 * @author ytf
 * Created by on 2021/06/02 08:25
 */
public class DetectionTrackerUtils {

    /**
     * 算两个人脸特征的相似度
     *
     * @param features1
     * @param features2
     * @return
     */
    public static float calculateSimilarity(float[] features1, float[] features2) {
        return ImoFaceExtractor.compare(features1, features2);
    }

    public static String saveNv21ToLocal(byte[] nv21, int w, int h, String path) {
        if (nv21 == null)
            return null;
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
            YuvImage image = new YuvImage(nv21, ImageFormat.NV21, w, h, null);
            image.compressToJpeg(new Rect(0, 0, w, h), 90, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            return path;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] NV21_mirror(byte[] nv21_data, int width, int height) {
        int i;
        int left, right;
        byte temp;
        int startPos = 0;

        // mirror Y
        for (i = 0; i < height; i++) {
            left = startPos;
            right = startPos + width - 1;
            while (left < right) {
                temp = nv21_data[left];
                nv21_data[left] = nv21_data[right];
                nv21_data[right] = temp;
                left++;
                right--;
            }
            startPos += width;
        }


        // mirror U and V
        int offset = width * height;
        startPos = 0;
        for (i = 0; i < height / 2; i++) {
            left = offset + startPos;
            right = offset + startPos + width - 2;
            while (left < right) {
                temp = nv21_data[left];
                nv21_data[left] = nv21_data[right];
                nv21_data[right] = temp;
                left++;
                right--;

                temp = nv21_data[left];
                nv21_data[left] = nv21_data[right];
                nv21_data[right] = temp;
                left++;
                right--;
            }
            startPos += width;
        }
        return nv21_data;
    }
}
